package cn.siriusbot.siriuspro.bot.event.impl;

import cn.siriusbot.siriuspro.admin.service.ServerConfigService;
import cn.siriusbot.siriuspro.bot.annotation.OnBotEvent;
import cn.siriusbot.siriuspro.bot.client.BotClient;
import cn.siriusbot.siriuspro.bot.event.WebHookEvent;
import cn.siriusbot.siriuspro.bot.event.v1.EventMethodHaveParam;
import cn.siriusbot.siriuspro.bot.pojo.e.BotEventType;
import cn.siriusbot.siriuspro.bot.pojo.event.BotEventMessage;
import lombok.extern.log4j.Log4j2;
import okhttp3.*;
import org.springframework.util.ObjectUtils;

import java.time.Duration;

@Log4j2
public class WebHookEventImpl implements WebHookEvent, EventMethodHaveParam<BotEventMessage> {

    /**
     * HttpClient单例
     */
    public static final OkHttpClient httpClient = new OkHttpClient.Builder()
            .callTimeout(Duration.ofSeconds(3))     // 设置超时时间为3秒
            .build();

    ServerConfigService serverConfigService;

    public WebHookEventImpl(ServerConfigService serverConfigService) {
        this.serverConfigService = serverConfigService;
    }


    /**
     * 注入客户端对象，并初始化
     */
    @Override
    public void init(BotClient client) {

    }

    /**
     * 机器人登录事件
     */
    @Override
    public void start() {

    }

    @OnBotEvent
    @Override
    public void onEvent(BotEventType type, BotEventMessage body) {
        String systemConfigHookUrl = serverConfigService.getString("system.config.hook.url");
        String[] split = systemConfigHookUrl.split(";");
        for (String url : split) {
            String hookUrl = url + "?token=" + serverConfigService.getString("system.config.hook.privateKey");
            if (!ObjectUtils.isEmpty(url)) {
                try {
                    RequestBody requestBody = RequestBody.create(body.getMessage(), MediaType.parse("application/json;text/plain"));
                    Request request = new Request.Builder()
                            .url(hookUrl)
                            .post(requestBody)
                            .build();
                    Response response = httpClient.newCall(request).execute();
                } catch (Exception e) {
                    log.warn("web_hook请求错误");
                }
            }
        }
    }
}
